import { defineStore } from 'pinia'
import axios from 'axios'

const useAPIStore = defineStore('api', {
  state: () => {
    return {
      count: 0,
      localIP: null,
      address: null,
      todayWeather:null,
      forecastWeather:null,
      inputValue:null,
      cityMessage:null
    }
  },
  getters: {},
  actions: {
    async fetchAddress() {
      try {
          const response = await axios.get(`https://restapi.amap.com/v3/ip?ip=114.247.50.2&key=fb204b26a7db9620f214f2d7ae7bf9e6`)
          this.address = response.data
      } catch (error) {
        console.error('Failed to fetch  address:', error)
      }
    },
    async fetchCityMessage(){
        try {
            if (this.inputValue) {
              const response = await axios.get(`https://restapi.amap.com/v3/geocode/geo?address=${this.inputValue}&key=fb204b26a7db9620f214f2d7ae7bf9e6`)
              this.cityMessage = response.data.geocodes
            }
          } catch (error) {
            console.error('Failed to fetch cityMessage:', error)
        }
    },
    async todayWeatherData (){
        try {
            if (!this.address&&!this.inputValue) {
              await this.fetchAddress()
              const response = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?city=${this.address.city}&key=fb204b26a7db9620f214f2d7ae7bf9e6`)
                this.todayWeather = response.data
            }else{
                const response = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?city=${this.inputValue}&key=fb204b26a7db9620f214f2d7ae7bf9e6`)
                this.todayWeather = response.data
            }
          } catch (error) {
            console.error('Failed to fetch todayWeather:', error)
          }
    },
    async forecastWeatherData (){
        try {
            if (!this.address&&!this.inputValue) {
              await this.fetchAddress()
              const response = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?city=${this.address.city}&key=fb204b26a7db9620f214f2d7ae7bf9e6&extensions=all`)
              this.forecastWeather = response.data
            }else{
                const response = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?city=${this.inputValue}&key=fb204b26a7db9620f214f2d7ae7bf9e6&extensions=all`)
                this.forecastWeather = response.data
            }
    
            
          } catch (error) {
            console.error('Failed to fetch forecastWeather:', error)
          }
    },
  },
})

export { useAPIStore }